package com.config.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.base.dao.TemplateDaoImpl;
import com.config.entity.Equipment;

@Repository(value="equipmentDao")
public class EquipmentDaoImpl extends TemplateDaoImpl<Equipment,Integer> implements EquipmentDao{
	
	@Override
	public List<Equipment> findByLine(Integer lineId,int start, int limit) {
		StringBuilder sb = new StringBuilder("select top "+limit+" * from (")
			.append("select row_number() over(order by id desc ) rowindex,* from ")
			.append(" equipment where 1=1");
		Map<String, Object> params=new HashMap<String, Object>();
		if(!StringUtils.isEmpty(lineId)){
			sb.append(" and lineId=:lineId");
			params.put("lineId", lineId);
		}
		sb.append(") u where u.rowindex>:start");
		params.put("start", (start-1)*limit);
		params.put("limit", limit);
		return jt.query(sb.toString(),params,
				ParameterizedBeanPropertyRowMapper.newInstance(Equipment.class));
	}

	@Override
	public int countByLine(Integer lineId) {
		StringBuffer sb = new StringBuffer("select count(*) from equipment where 1=1");
		Map<String, Object> params=new HashMap<String, Object>();
		if(!StringUtils.isEmpty(lineId)){
			sb.append(" and lineId=:lineId");
			params.put("lineId", lineId);
		}
		return jt.queryForObject(sb.toString(), params, Integer.class);
	}
	/**
	 * 根据生产线查询能采集数据的设备
	 * @param lineId
	 * @return
	 */
	@Override
	public List<Equipment> listByLine(Integer lineId) {
		StringBuffer sb = new StringBuffer(" select * from equipment where isCollect='Y' ");
		Map<String, Object> params=new HashMap<String, Object>();
		if(!StringUtils.isEmpty(lineId)){
			sb.append(" and lineId=:lineId");
			params.put("lineId", lineId);
		}
		return jt.query(sb.toString(),params,
				ParameterizedBeanPropertyRowMapper.newInstance(Equipment.class));
	}
	/**
	 * 根据设备类型查询设备
	 * @param equMoldId
	 * @return
	 */
	@Override
	public List<Equipment> findByEquModlId(int equMoldId) {
		StringBuffer sb = new StringBuffer(" select * from equipment where 1=1 ");
		Map<String, Object> params=new HashMap<String, Object>();
		if(!StringUtils.isEmpty(equMoldId)){
			sb.append(" and equMoldId=:equMoldId");
			params.put("equMoldId", equMoldId);
		}
		return jt.query(sb.toString(),params,
				ParameterizedBeanPropertyRowMapper.newInstance(Equipment.class));
	}

	@Override
	public Equipment getByEquNo(String equNo) {
		StringBuffer sb = new StringBuffer(" select * from equipment where equNo=:equNo ");
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("equNo", equNo);
		return jt.queryForObject(sb.toString(),params,
				ParameterizedBeanPropertyRowMapper.newInstance(Equipment.class));
	}
}
